from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class User(models.Model):
    """
    用户核心信息表（兼容 MySQL）
    """
    openid = models.CharField(max_length=100, unique=True, verbose_name="微信唯一标识")
    nickname = models.CharField(max_length=50, verbose_name="用户昵称")
    avatar_url = models.URLField(max_length=255, verbose_name="头像地址")
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="手机号")
    email = models.EmailField(max_length=100, blank=True, null=True, verbose_name="邮箱")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    is_admin = models.BooleanField(default=False, verbose_name="普通管理员")

    def __str__(self):
        return f"{self.nickname} (ID:{self.pk})"

class AEDEquipment(models.Model):
    """
    AED设备信息表（兼容 MySQL）
    """
    STATUS_CHOICES = (
        ('available', '可用'),
        ('unavailable', '不可用'),
        ('in_use', '正在使用'),
    )

    name = models.CharField(max_length=100, verbose_name="设备名称")
    longitude = models.FloatField(verbose_name="经度")  # MySQL 兼容的地理数据存储
    latitude = models.FloatField(verbose_name="纬度")    # 替代 PostGIS 的 PointField
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='available', verbose_name="设备状态")
    usage_guide = models.TextField(verbose_name="使用指南")
    image = models.ImageField(upload_to='aed_images/', blank=True, null=True, verbose_name="设备图片")  # 新增字段
    related_knowledge = models.ManyToManyField('Knowledge', through='EquipmentKnowledge', verbose_name="关联知识")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return f"{self.name} - {self.get_status_display()}"

class Knowledge(models.Model):
    """
    科普知识表（无修改）
    """
    title = models.CharField(max_length=200, verbose_name="知识标题")
    content = models.TextField(verbose_name="详细内容")
    category = models.CharField(max_length=50, verbose_name="知识分类")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return self.title

class VolunteerActivity(models.Model):
    """
    志愿服务表（无修改）
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='volunteer_activities', verbose_name="关联用户")
    task = models.CharField(max_length=200, verbose_name="服务内容")
    service_time = models.DateTimeField(verbose_name="服务时间")
    points = models.IntegerField(default=0, verbose_name="获得积分")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        ordering = ['-service_time']

    def __str__(self):
        return f"{self.user.nickname} | {self.task}"

class UserAuthentication(models.Model):
    """
    用户认证表
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='auth_info', verbose_name="关联用户")
    auth_token = models.CharField(max_length=255, verbose_name="认证令牌")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return f"{self.user.nickname} 的认证信息"

class ChatHistory(models.Model):
    """
    对话记录表（添加 session_id 字段用于多轮对话）
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_records', verbose_name="关联用户")
    message = models.TextField(verbose_name="用户提问")
    response = models.TextField(verbose_name="AI回复")
    session_id = models.CharField(max_length=100, verbose_name="会话ID", editable=False)  # 新增字段
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        ordering = ['created_at']

    def __str__(self):
        return f"{self.user.nickname} 的对话记录"


# 互动问答模块（仅修改外键引用）-------------------------------
class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='questions', verbose_name="提问用户")
    title = models.CharField(max_length=200, verbose_name="问题标题")
    content = models.TextField(verbose_name="问题详情")
    tags = models.ManyToManyField('Tag', blank=True, verbose_name="关联标签")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="最后编辑时间")

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"问题：{self.title[:20]}..."

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers', verbose_name="关联问题")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='answers', verbose_name="回答用户")
    content = models.TextField(verbose_name="回答内容")
    is_accepted = models.BooleanField(default=False, verbose_name="是否采纳")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="最后编辑时间")

    class Meta:
        ordering = ['created_at']

    def __str__(self):
        return f"对问题『{self.question.title}』的回答"

class Tag(models.Model):
   name = models.CharField(max_length=50, unique=True, verbose_name="标签名称")
   created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

   def __str__(self):
       return self.name

   @classmethod
   def create_default_tags(cls):
       default_tags = ['急救', '设备使用', 'AED维护', '心肺复苏', '急救知识']
       for tag_name in default_tags:
           cls.objects.get_or_create(name=tag_name)


class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments', verbose_name="评论用户")
    content = models.TextField(verbose_name="评论内容")
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name="父级评论")
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name="关联模型")
    object_id = models.PositiveIntegerField(verbose_name="关联对象ID")
    content_object = GenericForeignKey('content_type', 'object_id')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="评论时间")

    def __str__(self):
        return f"{self.user.nickname} 的评论"

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likes', verbose_name="点赞用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="点赞时间")
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name="关联模型")
    object_id = models.PositiveIntegerField(verbose_name="关联对象ID")
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = ('user', 'content_type', 'object_id')

    def __str__(self):
        return f"{self.user.nickname} 的点赞"

class EquipmentKnowledge(models.Model):
    equipment = models.ForeignKey(AEDEquipment, on_delete=models.CASCADE, verbose_name="关联设备")
    knowledge = models.ForeignKey(Knowledge, on_delete=models.CASCADE, verbose_name="关联知识")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="关联时间")

    class Meta:
        unique_together = ('equipment', 'knowledge')

    def __str__(self):
        return f"{self.equipment.name} ↔ {self.knowledge.title}"